package com.bigfreakindeals.Activities;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.util.EncodingUtils;
import org.w3c.dom.Text;

import com.bigfreakindeals.R;
import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Controller.ZipDownloader;
import com.bigfreakindeals.Models.ActiveDeal;
import com.bigfreakindeals.Models.PayPalObject;
import com.bigfreakindeals.Models.UniversityDeals;
import com.bigfreakindeals.Protocols.SoapHandlers.LoginWithFacebookHandler;
import com.bigfreakindeals.Protocols.SoapHandlers.PayPalWebHandler;
import com.bigfreakindeals.Widgets.AlertManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.LocalActivityManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalAdvancedPayment;
import com.paypal.android.MEP.PayPalInvoiceData;
import com.paypal.android.MEP.PayPalPayment;
import com.paypal.android.MEP.MEPAddress;
import com.paypal.android.MEP.PaymentAdjuster;
import com.paypal.android.MEP.MEPAmounts;

public class BuyActivity extends Activity implements OnClickListener {
	RelativeLayout mainpage;
	RelativeLayout maindeals; // grayed area deals page
	RelativeLayout maindealsNoDeals; // grayed area no deals

	RelativeLayout thumbnailLayout;

	RelativeLayout terms;
	View header;
	ListAdapter adapter;
	ListView dealListView;
	Button headerButtonLeft;
	Button headerButtonRight;
	TextView beanSays;
	Button share;
	Button discuss;

	Animation contextMenuIn;
	Animation contextMenuOut;

	TextView timer;
	Button beanSaysNoDeals;
	Long remainingTimer = (long) 0;

	TextView headerTitle;
	Button tf_highLights;
	Button tf_finePrint;
	Button tf_company;
	LinearLayout headertopBG;

	TextView textviewQuantity;
	TextView textviewAmount;
	TextView textviewPricetv;

	LinearLayout headerbottomBG;
	RelativeLayout tabtext_bg;
	TextView tabtext;
	WebView appView;
	TextView noDealsErrorMessage;
	ActiveDeal active = new ActiveDeal();
	UniversityDeals universitydeals;
	boolean hasdeals = true;

	List<ActiveDeal> dealList;
	double amount = 0.00, totalprice = 0.00;
	int quantity;
	String dealId;

	private static PayPal ppObj;
	private CheckoutButton _payPalButton;
		@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getActivityView();
	}
	public void updateBuyDetails(){
		initValue();
		refreshAmount();
	}
	public void getActivityView() {

		// init buy page scree
		setContentView(R.layout.buy);

		universitydeals = ApplicationEx.getInstance().myProfile.getlastSelectedSchool();
		if (universitydeals != null) {
			initValue();
		}
		textviewQuantity = (TextView) findViewById(R.id.quantity);
		textviewAmount = (TextView) findViewById(R.id.total);
		textviewPricetv = (TextView) findViewById(R.id.price);

		textviewQuantity.setOnClickListener(this);
		textviewAmount.setOnClickListener(this);
		textviewPricetv.setOnClickListener(this);

		((Button) findViewById(R.id.header_iconright)).setVisibility(View.GONE);
		((Button) findViewById(R.id.header_iconleft)).setVisibility(View.GONE);

		((RelativeLayout) findViewById(R.id.container)).setBackgroundColor(0xffffffff);
		((RelativeLayout) findViewById(R.id.buymainpage)).setBackgroundColor(0xffffffff);

		((Button) findViewById(R.id.minusbtn)).setBackgroundDrawable(ApplicationEx.getInstance().gradientGray_TOP_BOTTOM_BUY);
		((Button) findViewById(R.id.plusbtn)).setBackgroundDrawable(ApplicationEx.getInstance().gradientGray_TOP_BOTTOM_BUY);

		headertopBG = (LinearLayout) findViewById(R.id.headerbg_top);
		headerbottomBG = (LinearLayout) findViewById(R.id.headerbg_bottom);
		((ImageView) findViewById(R.id.paypalicon)).setOnClickListener(this);

		//refreshAmount();

		((View) findViewById(R.id.minusbtn)).setOnClickListener(this);
		((View) findViewById(R.id.plusbtn)).setOnClickListener(this);

		// Initialize PayPal Object and button
		
			PaypalButton asynch = new PaypalButton();
			asynch.execute(new Context[]{this.getParent().getBaseContext()});

		
	if (ppObj!=null){
			_payPalButton = ppObj.getCheckoutButton(this.getParent(),PayPal.BUTTON_278x43, PayPal.PAYMENT_TYPE_GOODS);
			_payPalButton.setOnClickListener(this);
	
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.BELOW, R.id.paypalicon);
		params.addRule(RelativeLayout.CENTER_HORIZONTAL);

		((RelativeLayout) findViewById(R.id.container)).addView(_payPalButton, params);
	}
	
	this.registerReceiver(broadcastReceiver, new IntentFilter(Constant.EVENTS_GETPAYPAL_IPN_SUCCESS));
	this.registerReceiver(broadcastReceiver, new IntentFilter(Constant.EVENTS_GETPAYPAL_IPN_ERROR));
	
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(broadcastReceiver);

	} 
	
	
	public BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Constant.EVENTS_GETPAYPAL_IPN_SUCCESS)) {
				callPayPalAPI();
			}else if (intent.getAction().equals(Constant.EVENTS_GETPAYPAL_IPN_ERROR)) {
				String errorMessage = intent.getStringExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE);
				displayErrorMessage(errorMessage);
			}

		}
	};
	
public void displayErrorMessage(String errorMessage){
		
		AlertManager.alertOK(this,errorMessage, "OK");
		
	}
	public void getPaybyCreditcard() {

		Intent i = new Intent(this, CreditCardActivity.class);
		i.putExtra("QUANTITY", "" + quantity);
		i.putExtra("DEALID", "" + dealId);
		i.putExtra("SESSIONID", "" + ApplicationEx.getInstance().myProfile.getSessionID());

		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

		LocalActivityManager local = ActiveDealsActivityGroup.activedealsgroup.getLocalActivityManager();
		// local.removeAllActivities();

		View view = local.startActivity("CreditPayment", i).getDecorView();

		ActiveDealsActivityGroup.activedealsgroup.replaceView(view);

	}



	public void refreshAmount() {

		totalprice = amount * quantity;

		String formatted = (new BigDecimal(String.valueOf(totalprice)).setScale(2, BigDecimal.ROUND_HALF_UP)).toString();
		textviewAmount.setText("$ " + formatted + "");
		
		formatted = (new BigDecimal(String.valueOf(amount)).setScale(2, BigDecimal.ROUND_HALF_UP)).toString();
		textviewPricetv.setText("$ " + formatted + "");
		textviewQuantity.setText(quantity + "");

	}

	public byte[] creditCardPaymentPostMethod(String dealid, String sessionid, int quantity) {
		String postData = "id_deal=" + dealid + "&sessionToken=" + sessionid + "&quantity=" + quantity;
		return EncodingUtils.getBytes(postData, "BASE64");
	}

	public void initValue() {

		String header = universitydeals.getSchoolTitle();
		ActiveDeal actve = universitydeals.getMainDeal();
		String dealtitle = actve.getDealName();
		dealId = actve.getDealID();
		amount = Tools.filterAmount(actve.getDiscountPrice());
		Constant.PAYPAL_DESCRIPTION = dealtitle + " " + dealId;
		quantity = 1;
		totalprice = amount * quantity;

		((TextView) findViewById(R.id.header_title)).setText(header);

		if (universitydeals.getColor_titleBarBottomColor() > -1 && universitydeals.getColor_titleBarTopColor() > -1) {
			if (headerbottomBG != null) {
				headerbottomBG.setBackgroundColor(universitydeals.getColor_titleBarBottomColor() + (-16777216));
			}
			if (headertopBG != null)
				headertopBG.setBackgroundColor(universitydeals.getColor_titleBarTopColor() + (-16777216));
		}
		((TextView) findViewById(R.id.dealtitle)).setText(dealtitle);
		
		if (universitydeals.getColor_titleBarBottomColor() > -1 && universitydeals.getColor_titleBarTopColor() > -1) {
			if (headerbottomBG != null) {
				headerbottomBG.setBackgroundColor(universitydeals.getColor_titleBarBottomColor() + (-16777216));
			}
			if (headertopBG != null)

				headertopBG.setBackgroundColor(universitydeals.getColor_titleBarTopColor() + (-16777216));
		}


	}

	private void gotoMyCoupons() {
		ApplicationEx.getInstance().currentTab = 1;
		getParent().onBackPressed();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		return super.onKeyDown(keyCode, event);
	}

	public void setConfirmAlert() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this.getParent());

		builder.setMessage("Do you want to go to your Coupons?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
				dialog.dismiss();
				ApplicationEx.getInstance().isConfirm = true;
				// TODO go to my coupons
				gotoMyCoupons();
			}
		}).setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
				ApplicationEx.getInstance().isConfirm = false;
				getParent().onBackPressed();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();

	}

	   public void initPayPalCall(){
			
			final ArrayList<String> param = new ArrayList<String>();
			param.add(ApplicationEx.getInstance().myProfile.getSessionID());
			param.add(ApplicationEx.getInstance().PayPal_dealId);
			param.add(ApplicationEx.getInstance().PayPal_dealquantity);
			 System.out.println("OnActivityResult = Success"+param.get(0)+" "+param.get(1)+" "+param.get(2));
			 
			new Thread() {
				@Override
				public void run() {
					try {
						sleep(5);
					} catch (Exception e) {
					}
					new PayPalWebHandler(Tools.getURL(Constant.GET_PAYPAL_IPN, param ));
					
				}

			}.start();
			
		}
	@Override
	public void onClick(View v) {
		System.out.println("onClick");
		if (v.getId() == R.id.minusbtn) {

			if (quantity > 0)
				quantity--;
			refreshAmount();
		} else if (v.getId() == R.id.plusbtn) {

			quantity++;
			refreshAmount();
		} else if (v.getId() == R.id.paypalicon) {
			getPaybyCreditcard();

		} else if (v.getId() == R.id.header_iconright) {
			setConfirmAlert();

		} else if (v == _payPalButton) {
			
			System.out.println("onClick");
			ApplicationEx.getInstance().PayPal_dealId = dealId;
			ApplicationEx.getInstance().PayPal_dealquantity = ""+quantity;
			
			initPayPalCall();
			
			
		}

	}
private void callPayPalAPI(){
	PayPalPayment newPayment = new PayPalPayment();
	PayPalObject obj = new PayPalObject();
	obj = ApplicationEx.getInstance().myProfile.paypalObj;
	if (obj !=null){
		newPayment.setSubtotal(new BigDecimal(obj.amount));
		newPayment.setCurrencyType(obj.currencycode);
		newPayment.setRecipient(obj.recipient);
		newPayment.setDescription(obj.itemname); // itemName
		newPayment.setMerchantName(Constant.PAYPAL_MERCHANT_NAME);
		if (obj.url_notify!=null){
			newPayment.setMemo(obj.getmemo());
			newPayment.setIpnUrl(obj.url_notify);
		}
		newPayment.setPaymentType(PayPal.PAYMENT_TYPE_SERVICE);
		PayPalInvoiceData invoice = new PayPalInvoiceData();
		
	     // Sets the tax amount.
	    invoice.setTax(new BigDecimal("0"));
	     // Sets the shipping amount.
	    invoice.setShipping(new BigDecimal("0"));
	
		newPayment.setInvoiceData(invoice);
		if (ppObj==null){
		 	ppObj = PayPal.initWithAppID(this.getParent(), "APP-80W284485P519543T", PayPal.ENV_SANDBOX);
	    }
	    
		Intent checkoutIntent = ppObj.checkout(newPayment, this.getParent()); 
	 	getParent().startActivityForResult(checkoutIntent, 1);
	}

	

	
}



	public void SignIn() {
		Intent intent = new Intent(this.getParent(), LoginActivity.class);
		intent.putExtra(Constant.TAG_LOGINFROM, Constant.TAG_LOGINFROM_BUYPAGE);
		startActivity(intent);
	}

	@Override
	public void onResume() {

		super.onResume();
		//System.out.println("onresume");
		//if (!ApplicationEx.getInstance().myProfile.isLogin()) {
			//this.getParent().onBackPressed();
		//	SignIn();

	//	} else {

			updateBuyDetails();
			

		//}

	}
	private void addPayPalButton(CheckoutButton check){
		
		((ProgressBar)findViewById(R.id.progress)).setVisibility(View.GONE);
		
		_payPalButton = check;
		
		_payPalButton.setOnClickListener(this);

		if (ppObj!=null){
			_payPalButton = ppObj.getCheckoutButton(this.getParent(),PayPal.BUTTON_278x43, PayPal.PAYMENT_TYPE_GOODS);
			_payPalButton.setOnClickListener(this);
	
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.BELOW, R.id.paypalicon);
		params.addRule(RelativeLayout.CENTER_HORIZONTAL);

		((RelativeLayout) findViewById(R.id.container)).addView(_payPalButton, params);
		}
	}
	public class PaypalButton extends AsyncTask<Context, Integer, CheckoutButton>
	{
		
		 @Override
		 protected  CheckoutButton doInBackground(Context... url)
	        {  CheckoutButton check = null;
	        if (ppObj==null)
	        	
	        	ppObj = PayPal.initWithAppID(url[0], "APP-80W284485P519543T", PayPal.ENV_SANDBOX);
	        else 
	        	ppObj = PayPal.getInstance();
				check = ppObj.getCheckoutButton(url[0],PayPal.BUTTON_278x43, PayPal.PAYMENT_TYPE_SERVICE);
	        	return check;
	        }
		 @Override
	        protected void onPostExecute(CheckoutButton check)
	        {
	                super.onPostExecute(check);
	                try {
	                	addPayPalButton(check);
	                }catch (Exception e) {
						// TODO: handle exception
	                }	
	          }
	}//paypalbutton asynch task
	
	

}
